﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using A2DFramework.ValidationService;

namespace A2DFramework.ContextService
{
    public sealed class CoreContext
    {
        internal CoreContext()
        {
            this.BrokenRulesContainer = new BrokenRulesContainer(this);
        }

        public static CoreContext Current
        {
            get
            {
                if(HttpContext.Current==null)
                    throw new Exception("不能在非Web环境下使用本库");

                if (HttpContext.Current.Items["A2DCoreContext"]==null)
                    HttpContext.Current.Items["A2DCoreContext"] = new CoreContext();

                object o = HttpContext.Current.Items["A2DCoreContext"];
                return (CoreContext)o;
            }
        }

        public void Save()
        {
            if (HttpContext.Current == null)
                throw new Exception("不能在非Web环境下使用本库");

            HttpContext.Current.Items["A2DCoreContext"] = this;
        }

        private Dictionary<string, object> dic = new Dictionary<string, object>();
        public void Set(string key, object o)
        {
            if (key == null || key.Length == 0)
                throw new Exception("Key不能为空");

            dic[key] = o;
        }
        public object Get(string key)
        {
            if (key == null || key.Length == 0)
                throw new Exception("Key不能为空");

            if (!dic.ContainsKey(key))
                return null;

            return dic[key];
        }

        public BrokenRulesContainer BrokenRulesContainer { get; private set; }
    }
}
